/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test_1;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class ServiceThread extends Thread {

    private Socket s = null;

    public ServiceThread(Socket s) throws Exception {
        this.s = s;



    }

    @Override
    public void run() {
        BufferedReader br = null;
        try {
            long start = System.currentTimeMillis();
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String result = br.readLine();
            //System.out.println(result);
            if (result != null) {
                //if(result.startsWith("GET")){
                //Pattern pattern = Pattern.compile("GET (.*) ");
                // pattern.matcher(result);
                if(result.indexOf("%") >= 0){
                    result = URLDecoder.decode(result, "utf-8");
                }
                result = result.replaceAll("^GET (.*) .*$", "$1");
                /*if ("".equals(result) || "/".equals(result)) {
                    result = "/index.html";
                } else if (result.indexOf(".") == -1) {
                    result = result + "/index.html";
                }*/
                boolean pL = false;
                
                if("..".equals(result)){
                    pL = true;
                    result = result.replace("..", "");
                }else if(result.matches("(jpg|JPG|gif|GIF|bmp|BMP|jpge|JPGE)")){

                }
                File file = new File(Main.docBase + result);
                if(pL)
                    file = file.getParentFile();
                    
                //System.out.println(docBase +  result);
               OutputStreamWriter outF = new OutputStreamWriter(s.getOutputStream(), Main.encode);
                if (file.exists()) {
                    
                   if(file.isFile()){
                       // DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
                        //dis.readByte();

                        DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
                        DataOutputStream ps = new DataOutputStream(s.getOutputStream());
                        //将文件名及长度传给客户端。这里要真正适用所有平台，例如中文名的处理，还需要加工，具体可以参见Think In Java 4th里有现成的代码。
                       // ps.writeUTF(file.getName());
                        //ps.flush();
                        //ps.writeLong((long) file.length());
                       // ps.flush();
                       

                        int bufferSize = 8192;
                        byte[] buf = new byte[bufferSize];
                      
                        while (true) {
                            int read = 0;
                            if (fis != null) {
                                read = fis.read(buf);
                            }

                            if (read == -1) {
                                break;
                            }
                            ps.write(buf, 0, read);
                        }
                           //ps.writeChars("Accept-Charset:utf-8");
                        ps.flush();
                        // 注意关闭socket链接哦，不然客户端会等待server的数据过来，
                        // 直到socket超时，导致数据不完整。
                        //dis.close();
                        fis.close();
                       
                        s.close();
                         ps.close();
                    }
                   else{
                         
                        String fis []= file.list();
                        outF.write("<html>\n");
                        outF.write("<head>\n");
                        outF.write("<meta http-equiv='Content-Type' content='text/html; charset="+Main.encode+"' />\n");
                        outF.write("</head>\n");
                        outF.write("<base href='http://localhost:"+Main.port+result.replaceAll("(/+)$", "")+"/'/>\n");
                        outF.write("<body style='margin-left:100px;'>\n");
                         outF.write("          当前目录："+result.replaceAll("(/+)$", "/")+"<br/>\n");
                        outF.write("          <a href='..'>..</a><br/>\n");
                            if(fis !=null && fis.length>0){
                                for(int i = 0 ; i < fis.length ; i++)
                                    outF.write("          <a href='"+fis[i]+"'>"+fis[i]+"</a><br/>\n");
                            }
                        outF.write("</body>\n");
                        outF.write("</html>");
                         //outF.close();
                   }
                   
                   
                }
                else
                {
                   outF.write("<html>\n");
                        outF.write("<head>\n");
                        outF.write("<meta http-equiv='Content-Type' content='text/html; charset="+Main.encode+"' />\n");
                        outF.write("</head>\n");
                        outF.write("<base href='http://localhost:"+Main.port+result.replaceAll("(/+)$", "")+"/'/>\n");
                        outF.write("<body style='margin-left:100px;'>\n");
                        outF.write("          当前目录："+result.replaceAll("(/+)$", "/")+"<br/>\n");
                         outF.write("          <a href='..'>..</a><br/>\n");
                        outF.write("<font color=red>404 文件或目录不存在</font>\n");
                        outF.write("</body>\n");
                        outF.write("</html>");
                    

                }
                 outF.close();

            } else {
                //outF.write(result+"未找到 ");
            }
            s.close();
            System.out.println(result + " time=" + (System.currentTimeMillis() - start));
        }
        //String r = null;
        /* while((r = br.readLine()) != null){
        System.out.println("result:,"+r+",");
        result.append(r);
        }*/
        //System.out.println("result:111"+result.toString());
        //server.close();
        catch (IOException ex) {
            Logger.getLogger(ServiceThread.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                br.close();
            } catch (IOException ex) {
                Logger.getLogger(ServiceThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }


            }
            //String r = null;
           /* while((r = br.readLine()) != null){

                System.out.println("result:,"+r+",");
                result.append(r);
            }*/
             //System.out.println("result:111"+result.toString());



            //server.close();
    
}
